import React, { useEffect, useState } from 'react';
import { history, useModel } from 'umi';
import { Alert, message, Button } from 'antd';
import moment from 'moment';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';

import { userLogin, slideLogin } from '@/services/system.service';
import StorageManager from '@/utils/StorageManager';
import styles from './index.less';

type TLoginResult = {
  status?: string;
  type?: string;
  loginMsg?: string;
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<TLoginResult>({});
  const { initialState, setInitialState } = useModel('@@initialState');
  const { settings: { title = '' } = {} } = initialState || {};

  const clearInitialState = () => {
    const token = StorageManager.getCookie('token');
    if (!token) {
      setInitialState((s) => ({
        ...s,
        currentUser: undefined,
        imgPrefix: '',
        districtMap: [],
        menuMap: [],
        menuKeyMap: {},
        merchantMap: [],
        merchantId: '',
      }));
    }
  };

  const fetchUserInfo = async () => {
    const currentUserInfo = await initialState?.fetchUserInfo?.();
    if (currentUserInfo) {
      await setInitialState((s) => ({
        ...s,
        ...currentUserInfo,
        currentUser: currentUserInfo,
      }));
      history.push('/');
    }
  };

  // 处理登录数据
  const handleLoginData = (data: TUserApi.TLoginRes) => {
    const { ticket, endTime } = data;
    const now = new Date().valueOf();
    const endTimeValue = moment(endTime).valueOf();
    const expiration = Math.floor((endTimeValue - now) / 1000);
    StorageManager.setCookie('token', ticket, expiration);
  };

  const handleSubmit = async (values: any) => {
    // 登录
    const res = await slideLogin({ ...values });
    console.log('嘎嘎嘎--登录', res);
    if (res && res.token) {
      message.success('登录成功')
      history.push('/dashboard');
      StorageManager.setSessionStorageSimpleSync('storage-token', res.token);
      StorageManager.setSessionStorageSimpleSync('storage-email', values.email);
    } else {
      message.error('邮件账号或密码错误');
    }
    // slideLogin
    // history.push('/');
    return;
    // try {
    //   // 登录
    //   const { code, data, errorData, message: msg } = await userLogin({ ...values });
    //   if (code === 0) {
    //     const defaultLoginSuccessMessage = '登录成功！';
    //     message.success(defaultLoginSuccessMessage);
    //     handleLoginData(data);
    //     await fetchUserInfo();
    //     return;
    //   }
    //   const { thirdErrorMessage } = errorData || {};
    //   setUserLoginState({ status: 'error', type: 'account', loginMsg: thirdErrorMessage || msg });
    // } catch (error) {
    //   const defaultLoginFailureMessage = '登录失败，请重试！';
    //   message.error(defaultLoginFailureMessage);
    // }
  };

  useEffect(() => {
    clearInitialState();
  }, []);

  const { status, type: loginType, loginMsg } = userLoginState;
  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          // logo={<img alt="logo" src="./images/logo.png" />}
          contentStyle={{ marginTop: '36px' }}
          title={'welcome to ' + title}
          initialValues={{ autoLogin: true }}
          onFinish={async (values) => await handleSubmit(values as TUserApi.TLoginParams)}
        >
          {status === 'error' && loginType === 'account' && (
            <Alert
              style={{ marginBottom: 24 }}
              message={loginMsg || '登录失败'}
              type="error"
              showIcon
            />
          )}
          <ProFormText
            name="email"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined className={styles.prefixIcon} />,
            }}
            placeholder="电子邮件"
            rules={[
              { required: true, message: '电子邮件是必填项！' },
              {
                pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
                message: '电子邮件格式不正确！',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            placeholder="密码"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined className={styles.prefixIcon} />,
            }}
            rules={[{ required: true, message: '密码是必填项！' }]}
          />
        </LoginForm>
        <div style={{ float: 'right', marginTop: -20 }}>
          <Button type="link" onClick={() => history.push('/register')}>
            去注册
          </Button>
        </div>
      </div>
    </div>
  );
};

export default Login;
